<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>
        div {
            height: 100px;
            width: 100px;
            background: red;
            position: absolute;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        var div = document.querySelector("div"),
            flag = false,
            pos = null

        div.addEventListener("mousedown", function (e) {
            flag = true
            pos = {
                x: e.offsetX,
                y: e.offsetY
            }
        })
        document.addEventListener("mousemove", function (e) {
            if (flag) {
                var x = e.pageX - pos.x
                var y = e.pageY - pos.y
                if (x < 0) {
                    x = 0
                }

                if (y < 0) {
                    y = 0   
                }

                if (x > document.documentElement.clientWidth - div.offsetWidth) {
                    x = document.documentElement.clientWidth - div.offsetWidth
                }
                if (y > document.documentElement.clientHeight - div.offsetHeight) {
                    y = document.documentElement.clientHeight - div.offsetHeight
                }

                div.style.left = x + "px"
                div.style.top = y + "px"



            }
        })
        document.addEventListener("mouseup", function () {
            if (flag) {
                flag = false
            }
        })


    </script>
</body>

</html>